import { Link, useNavigate } from 'react-router-dom'
import { Card, Breadcrumb, Form, Button, Radio, DatePicker, Select, Table, Tag, Space, TableProps, Popconfirm, message } from 'antd'
import locale from 'antd/es/date-picker/locale/zh_CN'
import { EditOutlined, DeleteOutlined } from '@ant-design/icons'
import useChannel from '@/hooks/useChannel';
import { ArticleItemType, SelectArticleParamsType, deleteArticleAPI, selectArticleAPI } from '@/apis/articleApi';
import { useCallback, useEffect, useState } from 'react';
import ErrorResolveImage from '@/components/ErrorResolveImage/ErrorResolveImage';
import { RangePickerProps } from 'antd/es/date-picker';
import FormSubmitButton from '@/components/FormSubmitButton/FormSubmitButton';

const { Option } = Select
const { RangePicker } = DatePicker

type CoverType = {
    images: Array<string>,
    type: string,
};

type FilterArticleFormType = {
    status?: number,
    channel_id?: number,
    date?: RangePickerProps['value'],
};

type TablePagination = NonNullable<Exclude<TableProps['pagination'], boolean>>;

// 文章表格
const ArticleTable = ({ dataSource, pagination, onDelete }: { dataSource: Array<ArticleItemType>, pagination: TablePagination, onDelete: (id: string) => void }) => {
    const navigate = useNavigate();

    // 准备列数据
    const columns = [
        {
            title: '封面',
            dataIndex: 'cover',
            width: 120,
            render: (cover: CoverType) => {
                return <ErrorResolveImage src={cover.images[0]} width={80} height={60} />
            }
        },
        { title: '标题', dataIndex: 'title', width: 220 },
        {
            title: '状态',
            dataIndex: 'status',
            render: (data: number) => {
                switch (data) {
                    case 1:
                        return <Tag color="orange">审核中</Tag>;
                    case 2:
                        return <Tag color="green">审核通过</Tag>;
                }
            },
        },
        { title: '发布时间', dataIndex: 'pubdate' },
        { title: '阅读数', dataIndex: 'read_count' },
        { title: '评论数', dataIndex: 'comment_count' },
        { title: '点赞数', dataIndex: 'like_count' },
        {
            title: '操作',
            render: (data: ArticleItemType) => {
                return (
                    <Space size="middle">
                        <Button type="primary" shape="circle" icon={<EditOutlined />} onClick={() => navigate(`/publish?id=${data.id}`)} />
                        <Popconfirm title='是否删除此篇文章？'
                            onConfirm={() => onDelete(data.id)}
                            okText='确认'
                            cancelText='取消'>
                            <Button type="primary" danger shape="circle" icon={<DeleteOutlined />} />
                        </Popconfirm>
                    </Space>
                );
            }
        },
    ];

    return (
        <Card title={`根据筛选条件共查询到 ${pagination.total} 条结果：`}>
            <Table rowKey="id" columns={columns} {...{ dataSource, pagination }} />
        </Card>
    );
};

const Article = () => {
    // 频道hook
    const { channels } = useChannel();

    // 文章列表
    const [articles, setArticles] = useState<{ list: Array<ArticleItemType>, count: number }>({ list: [], count: 0 });

    // 文章分页参数
    const [pageParams, setPageParams] = useState({
        page: 1,
        per_page: 4,
    });

    // 加载状态
    const [loading, setLoading] = useState(false);

    // 查询筛选文章信息
    const selectArticles = useCallback((requestData?: SelectArticleParamsType) => {
        setLoading(true);
        selectArticleAPI({ ...requestData, ...pageParams }).request.then(response => {
            setLoading(false);
            const { results, total_count } = response.data;
            setArticles({ list: results, count: total_count });
        }).catch(() => {
            setLoading(false);
        });
    }, [pageParams]);

    // 删除文章
    const deleteArticle = (id: string) => {
        deleteArticleAPI(id).request.then(() => {
            message.success('删除成功！');
            // 更新列表
            setPageParams({ page: 1, per_page: 4 });
        }).catch(error => {
            message.error(error.response.message);
        });
    };

    // 初始化文章信息
    useEffect(() => {
        selectArticles({ ...pageParams });
    }, [pageParams, selectArticles]);

    // 筛选文章
    const select = (filterParams: FilterArticleFormType) => {
        const { status, channel_id, date } = filterParams;
        const begin_pubdate = (date || [])[0]?.format('YYYY-MM-DD');
        const end_pubdate = (date || [])[1]?.format('YYYY-MM-DD');
        selectArticles({ status, channel_id, begin_pubdate, end_pubdate });
    };

    return (
        <div>
            <Card title={
                <Breadcrumb items={[
                    { title: <Link to={'/'}>首页</Link> },
                    { title: '文章列表' },
                ]} />}
                style={{ marginBottom: 20 }}>
                <Form initialValues={{ status: void 0 }} onFinish={select} layout='inline'>
                    <Form.Item label="状态" name="status">
                        <Radio.Group>
                            <Radio value={void 0}>全部</Radio>
                            <Radio value={0}>草稿</Radio>
                            <Radio value={2}>审核通过</Radio>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item label="频道" name="channel_id">
                        <Select
                            placeholder="请选择文章频道"
                            style={{ width: 120 }}>
                            {channels.map(item => (
                                <Option key={item.id} value={item.id}>{item.name}</Option>
                            ))}
                        </Select>
                    </Form.Item>
                    <Form.Item label="日期" name="date">
                        {/* 传入locale属性 控制中文显示*/}
                        <RangePicker locale={locale}></RangePicker>
                    </Form.Item>
                    <Form.Item>
                        <FormSubmitButton size='middle' text='筛选' loading={loading} />
                    </Form.Item>
                </Form>
            </Card>
            <ArticleTable dataSource={articles.list} pagination={{
                current: pageParams.page,
                pageSize: pageParams.per_page,
                onChange: (page, pageParams) => { setPageParams({ page, per_page: pageParams }) },
                total: articles.count,
            }}
                onDelete={deleteArticle} />
        </div>
    );
};

export default Article;